package com.fancy.mobileschool.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.fancy.mobileschool.entity.HduNews;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;



public class Spider {
	
	public static String  originalUrl="http://www.hdu.edu.cn/news/important";
	public static String t_originalUrl="http://www.hdu.edu.cn/";
	
	
	
	public  static List<String> getUrls(int num)
	{
		List<String> res=new ArrayList<String>();
		Document document =null;
		try{
			document=Jsoup.connect(originalUrl).get();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}


		if (document != null){
			Elements elements=document.select("div.item>a");
			int i=0;
			for(Element element:elements)
			{
				res.add(t_originalUrl+element.attr("href"));
				i++;
				if(i==num)break;
			}
		}

		return res;
	}


	public  static List<String> getTitles(int num)
	{
		List<String> res=new ArrayList<String>();
		Document document =null;
		Elements elements = null;
		try{
			document=Jsoup.connect(originalUrl).get();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}

		if(document!=null)
		{
		 elements=document.select("div.item>a");
		}
		if(elements!=null){
			int i=0;
			for(Element element:elements)
			{
				res.add(element.attr("title"));
				i++;
				if(i==num)break;
			}
		}
		return res;
	}
	
	
	
	public static HduNews getNews(String url)
	{
		HduNews hduNews=new HduNews();
		Document document=null;
	
		try {
			document=Jsoup.connect(url).get();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//文章标题
		Element title=document.select("div.news_title").first();
		if(title!=null)
		{
		 hduNews.setTitle(title.text());
		}
		
		Element info=document.select("div.news_info").first();
		if(info!=null)
		{
			hduNews.setInfo(info.text());
		}
		
		
		//文章内容
		Elements content=document.select("div.news_content>p");
		StringBuffer sb=new StringBuffer();
		if(content!=null)
		{
			for(Element pragrah:content)
			{
				sb.append(pragrah.text()+"\n");
			}
		}
		hduNews.setContent(sb.toString());


		//图像
		Element img=document.select("div.news_content>p>img").first();
		if(img!=null)
		{
			String imgUrl="http://www.hdu.edu.cn"+img.attr("src");
			try {
				URL url1=new URL(imgUrl);
				Bitmap bitmap= BitmapFactory.decodeStream(url1.openStream());
				hduNews.setBitmap(bitmap);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}


		return hduNews;
		
	}
}
